<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width="1000"
    :visible="visible"
    :confirm-loading="loading"
    :title="user.roleId && user.roleId === '2'? '查看代理商详情' :(isUpdate ? '修改代理商' : '新建代理商')"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-card :bordered="false">

      <a-form
        layout="horizontal"
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 6 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }"
      >

        <a-row :gutter="8">
          <a-col :span="12">
            <a-form-item label="代理商名称:" name="name">
              <a-input :disabled="shouldDisableUpdate" v-model:value="form.name" placeholder="请输入代理商名称" maxlength="20" allow-clear autocomplete="off"
                      />
            </a-form-item>
            <a-form-item label="级别:" name="level">
              <a-select
                :disabled="shouldDisableUpdate"
                placeholder="请选择级别"
                v-model:value="form.level"
                show-search
                allow-clear>
                <a-select-option value="金牌代理商">金牌代理商</a-select-option>
                <a-select-option value="银牌代理商">银牌代理商</a-select-option>
                <a-select-option value="铜牌代理商">铜牌代理商</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="所在地区:" name="address">
              <a-input :disabled="shouldDisableUpdate" v-model:value="form.address" placeholder="请输入所在地区" maxlength="50" allow-clear autocomplete="off" />
            </a-form-item>
            <a-form-item label="代理商有效期:" name="expirationDateRange">
              <a-range-picker  :disabled="shouldDisableUpdate"
                               v-model:value="form.expirationDateRange"
                              :show-time="false"
                              value-format="YYYY-MM-DD"
                              class="ele-fluid">
                <template #suffixIcon>
                  <calendar-outlined />
                </template>
              </a-range-picker>
            </a-form-item>

          </a-col>
          <a-col :span="12">

            <a-form-item label="联系人姓名:" name="contactName">
              <a-input :disabled="shouldDisableUpdate" v-model:value="form.contactName" placeholder="请输入联系人姓名" maxlength="50" allow-clear autocomplete="off"
                       />
            </a-form-item>
            <a-form-item label="联系人电话:" name="contactPhone">
              <a-input :disabled="shouldDisableUpdate" v-model:value="form.contactPhone" placeholder="请输入联系人电话最多11位" allow-clear autocomplete="off"
                       maxlength="11" />
            </a-form-item>
            <a-form-item label="联系人邮箱:" name="contactMail">
              <a-input :disabled="shouldDisableUpdate" v-model:value="form.contactMail" placeholder="请输入联系人邮箱最多50个字" maxlength="50" allow-clear autocomplete="off"
                      />
            </a-form-item>
            <a-form-item label="所在地域:" name="region">
              <a-select
                        :disabled="shouldDisableUpdate"
                        placeholder="所在地域"
                        v-model:value="form.region"
                        show-search
                        allow-clear>
                <a-select-option v-for="region in regionList" :key="region" :value="region">
                  {{ region }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="负责区域:" :label-col="{span:3}" :wrapper-col="{span:9}" name="area">
              <a-select
                        :disabled="shouldDisableUpdate"
                        placeholder="负责区域"
                        v-model:value="form.area"
                        mode="multiple"
                        style="width: 100%"
                        show-arrow
                        show-search
                        allow-clear>
                <a-select-option v-for="item in areaList" :key="item.name" :value="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="logo:" name="logoFileId">
              <a-upload
                :disabled="shouldDisableUpdate"
                accept="image/png,image/jpeg"
                :headers="headers"
                action="/api/sysFileInfo/upload?secretFlag=N"
                list-type="picture-card"
                v-model:file-list="fileList"
                @preview="handlePreview"
              >
                <div v-if="fileList.length < 1">
                  <PlusOutlined class="ele-image-upload-icon" />
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <template #footer>
      <div>
        <a-button v-if="user.roleId === '2'" type="primary" @click="updateVisible()">关闭</a-button>
        <a-button v-if="user.roleId !== '2'" @click="updateVisible()" style="margin-left: 20px">取消</a-button>
        <a-button v-if="user.roleId !== '2'" type="primary" @click="save()">确定</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import { onMounted, ref } from 'vue';
import setting from '@/config/setting';
import { CalendarOutlined } from '@ant-design/icons-vue';
import { AgentApi } from '@/api/AgentApi';
import { AreaApi } from '@/api/AreaApi';
import { DashboardApi } from '@/api/DashboardApi';

export default {
  name: 'PositionEdit',
  components: { CalendarOutlined },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  setup() {
    // 加载下拉数据
    const areaList = ref([]);
    const regionList = ref([]);

    onMounted(async () => {
      const res = await AreaApi.findList({ sharing: 2 });
      areaList.value = res.data;
      const res2 = await AgentApi.findRegionList({});
      regionList.value = res2.data;

    });

    const beforeUpload = () => {
      return true;
    };
    const fileList = ref([]);

    return {
      areaList,
      regionList,
      beforeUpload,
      fileList
    };
  },
  data() {
    return {
      // 用户信息
      user: {},
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        name: [{ required: true, message: '请输入代理商名称', type: 'string', trigger: 'blur' }],
        level: [{ required: true, message: '请选在代理商级别', type: 'string', trigger: 'blur' }],
        address: [{ required: true, message: '请选择所在地区', type: 'string', trigger: 'blur' }],
        contactName: [{ required: true, message: '请输入联系人姓名', type: 'string', trigger: 'blur' }],
        contactPhone: [{ required: true, message: '请输入联系人电话', type: 'string', trigger: 'blur' }],
        contactMail: [{ required: true, message: '请输入联系人邮箱', type: 'string', trigger: 'blur' }],
        //logoFileId: [{ required: true, message: '请上传logo', trigger: 'blur' }],
        region: [{ required: true, message: '请选择所在地域', type: 'string', trigger: 'blur' }],
        expirationDateRange: [{ required: true, message: '请选择代理商有效期', trigger: 'change' ,
          validator: (rule, value, callback) => {
            console.log(this.form.area);
            if(this.form.expirationDateRange && this.form.expirationDateRange.length > 1
              && this.form.expirationDateRange[0] && this.form.expirationDateRange[1]){
              callback();
            }else{
              callback(new Error('负责区域不能为空'));
            }
          }}],
        area: [{ required: true, message: '请选择负责区域', trigger: 'change',
          validator: (rule, value, callback) => {
            console.log(this.form.area);
            if(this.form.area && this.form.area.length > 0){
              callback();
            }else{
              callback(new Error('负责区域不能为空'));
            }
          }}]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 上传图片时候的header
      headers: {
        Authorization: setting.takeToken()
      },
      // 是否可以预览
      previewVisible: false,
      // 预览图片的地址
      previewImage: '',
      // 表单禁用
      shouldDisableUpdate: false,
    };
  },
  watch: {
    visible() {
      // 弹窗打开
      if (!this.data) {
        // 新增-清除表格内容
        this.form = {};
        this.fileList = [];
      } else {
        // 当弹窗打开时，重置data的值
        this.form = Object.assign({}, this.data);
      }
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }

      // 营业者查看 代理商信息-详情，所有项禁用(不用置灰)，按钮只保留 关闭
      if(this.user.roleId === '2'){
        this.shouldDisableUpdate = true;
      }else{
        this.shouldDisableUpdate = false;
      }
    },
    data() {
      if (this.data) {
        // 编辑的时候适配组件数据类型
        // this.data.area = this.data.area.split(',');
        if (typeof this.data.area === 'string') {
          this.data.area = this.data.area.split(','); // 假设你想根据逗号分割
        }
        /*else {
          console.error('data.area is not a string');
          // 处理非字符串的情况，比如抛出更友好的错误提示或赋予默认值
        }*/
        this.data.expirationDateRange = [this.data.expirationDateStart, this.data.expirationDateEnd];

        this.form = Object.assign({}, this.data);
        //文件列表赋值
        this.isUpdate = true;
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.fileList = [{
          name: '',
          url: `/api/sysFileInfo/public/preview?fileId=${this.data.logoFileId}&token=${token}`
        }];
      } else {
        // 新增-清除表格内容
        this.form = {};

        // 新增-文件列表内容
        this.fileList = [];

        this.isUpdate = false;
      }
      // 清空表单校验信息
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    }
  },
  mounted() {
    this.getUser();
  },
  methods: {
    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },
    /**
     * 保存和编辑职务
     */
    async save() {
      if (this.user.roleId && this.user.roleId === '2') {
        this.$message.error('您无权限编辑代理商');
        return;
      }
      // 校验表单
      await this.$refs.form.validate();

      // 校验联系人电话格式
      if (!/^\d{1,}-?\d*$/.test(this.form.contactPhone)) {
        this.$message.error('请输入正确的联系人电话');
        return;
      }
      // 校验联系人电话格式是11位
      if (this.form.contactPhone.length !== 11) {
        this.$message.error('请输入11位联系人电话');
        return;
      }
      // 校验联系人邮箱格式
      if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.form.contactMail)) {
        this.$message.error('请输入正确的联系人邮箱');
        return;
      }

      // 设置logo图片 id
      if (this.fileList.length > 0) {
        if (this.fileList[0]?.response) {
          this.form.logoFileId = this.fileList[0].response.data.fileId;
        }
      }
      // 设置开始结束时间
      if (this.form.expirationDateRange) {
        this.form.expirationDateStart = this.form.expirationDateRange[0];
        this.form.expirationDateEnd = this.form.expirationDateRange[1];
      }

      // 设置地区
      if (this.form.area) {
        this.form.area = this.form.area.join(',');
      }

      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = AgentApi.edit(this.form);
      } else {
        result = AgentApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          this.$message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          console.log('catch error')
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     * @param value true-显示，false-隐藏
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    /**
     * 点击预览图片时
     */
    handlePreview(file) {
      // 打开预览框
      this.previewVisible = true;
      // 获取到文件id
      let fileId = file?.response?.data?.fileId;
      if (!fileId) {
        // 拼接文件预览的url
        this.previewImage = file.url;
      } else {
        // 拼接文件预览的url
        let token = setting.takeToken();
        this.previewImage = `/api/sysFileInfo/public/preview?fileId=${fileId}&token=${token}`;
      }
    },

    /**
     * 点击取消按钮
     */
    handleCancel() {
      this.previewVisible = false;
    }
  }
};
</script>


<style scoped>
/*.ele-image-upload-icon {
  font-size: 22px;
  color: @text-color-secondary;
  opacity: 0.8;
}*/
/deep/.ant-input-disabled {
  background-color: white !important;
  color: black !important;
}

/deep/.ant-select-selector {
  background-color: white !important;
  color: black !important;
}

/deep/.ant-select-selection-item {
  background-color: white !important;
  color: black !important;
}


</style>
